<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<title>角色管理</title>
<script type="text/javascript">
	var selectedRole;
	var $grid;
	var menuTree;
	var action = "xz", act = "sz";//标识treegrid为点击勾选状态
	$(function() {
		//初始化角色列表
		$grid = $("#grid").datagrid($.extend(datagridOption, {
			url : "${ctx}/basic/role/dataGrid",
			columns : [ [ {
				field : 'ck',
				checkbox : true
			}, {
				field : 'roleName',
				title : '角色名称',
				sortable : true
			}, {
				field : 'roleNo',
				title : '角色编号',
				sortable : true
			} ] ],
			onClickRow : function(rowIndex, rowData) {
				selectedRole = rowData;
				refreshMenuTree();//刷新当前角色的菜单
				refreshRoleFunctions();
			}
		}));
		$grid.datagrid('enableFilter');
		//初始化菜单列表
		menuTree = $("#menuTree").treegrid({
			title : "菜单权限",
			fit : true,
			toolbar : "#menuTool",
			method : "get",
			url : "${ctx}/basic/menu/treeGridWithFunctions",
			idField : 'id',
			treeField : 'menuName',
			remoteSort : false,
			singleSelect : true,
			selectOnCheck : false,// 当用户仅在点击该复选框的时候才会选中或取消
			checkOnSelect : false,// 选择行将不选中复选框
			cascadeCheck : false,//级联勾选
			dataPlain : true, //该属性用以启用当前 easyui-treegrid 控件对平滑数据格式的支持
			parentField : "menuParentId",
			//enableRowContextMenu : true,// 此属性开启行右键点击菜单
			onUncheck : function(row) {
				$(".chkFunc[menuId='" + row.id + "']").removeAttr("checked");
				if (act != "fx") {
					var nodes = menuTree.treegrid('getChildren', row.id);
					if (nodes[0] != null && nodes.length >= 0) {
						act = "jl";
						for (var i = 0; i < nodes.length; i++) {
							menuTree.treegrid("uncheck", nodes[i]);
						}
						act = "sz";
					}
				}
				if (act != "jl") {
					var j = 0;
					if (row.menuParentId == null) {
						act = "sz";
						return false;
					}
					var node = menuTree.treegrid('find', row.menuParentId);
					var nodeps = menuTree.treegrid('getChildren', row.menuParentId);
					if (nodeps[0] != null && nodeps.length >= 0) {
						for (var i = 0; i < nodeps.length; i++) {
							if (menuTree.treegrid('isChecked', nodeps[i].id)) {
								j++;
								act = "sz";
								break;
							}
						}
					}
					if (j == 0) {
						act = "fx";
						menuTree.treegrid("uncheck", node);
					}
				}
			},
			onCheck : function(row) {
				$(".chkFunc[menuId='" + row.id + "'][functionno='list']").prop("checked", true);
				if (action == "fz" || action == "jl") {
					if (row.menuParentId != null && row.menuParentId != "") {
						var node = menuTree.treegrid("find", row.menuParentId);
						menuTree.treegrid("check", node);
					}
				} else if (action == "xz") {
					var nodes = menuTree.treegrid('getChildren', row.id);
					action = "jl";
					if (nodes[0] != null) {
						for (var i = 0; i < nodes.length; i++) {
							menuTree.treegrid("check", nodes[i]);
						}
					} else {
						if (row.menuParentId != null && row.menuParentId != "") {
							var node = menuTree.treegrid("find", row.menuParentId);
							menuTree.treegrid("check", node);
						}
					}
					action = "xz";
				}
			},
			onSelect : function(row) {
				var a = $(".chkFunc[menuId=" + row.id + "]:checked");
				if (a[0] == null || a.length < 0) {
					return false;
				} else {
					var node = menuTree.treegrid("find", row.id);
					menuTree.treegrid("check", node);
				}
			},
			rowContextMenu : [ {
				text : "全选当前行",
				iconCls : "icon-metro-checkbox-checked",
				disabled : false,
				handler : function(e, row) {
					var nodes = menuTree.treegrid('getChildren', row.id);
					if (nodes[0] != null && nodes.length >= 0) {
						return false;
					}
					var node = menuTree.treegrid("find", row.id);
					menuTree.treegrid("check", node);
					var a = $(".chkFunc[menuId=" + row.id + "]");
					a.each(function() {
						$(this).prop("checked", true);
					});
				}
			}, {
				text : "取消当前行",
				iconCls : "icon-metro-checkbox-unchecked",
				disabled : false,
				handler : function(e, row) {
					var node = menuTree.treegrid("find", row.id);
					menuTree.treegrid("uncheck", node);
				}
			}, "-", {
				text : "全选当前树",
				iconCls : "icon-metro-checkbox-checked",
				disabled : false,
				handler : function(e, row) {
					var nodes = menuTree.treegrid('getChildren', row.id);
					if (nodes[0] == null && nodes.length <= 0) {
						var node = menuTree.treegrid("find", row.menuParentId);
						menuTree.treegrid("check", node);
						nodes = menuTree.treegrid('getChildren', row.menuParentId);
						for (var i = 0; i < nodes.length; i++) {
							var a = $(".chkFunc[menuId=" + nodes[i].id + "]");
							a.each(function() {
								$(this).prop("checked", true);
							});
						}
					} else {
						var node = menuTree.treegrid("find", row.id);
						menuTree.treegrid("check", node);
						nodes = menuTree.treegrid('getChildren', row.id);
						for (var i = 0; i < nodes.length; i++) {
							var a = $(".chkFunc[menuId=" + nodes[i].id + "]");
							a.each(function() {
								$(this).prop("checked", true);
							});
						}
					}
				}
			}, {
				text : "取消当前树",
				iconCls : "icon-metro-checkbox-unchecked",
				disabled : false,
				handler : function(e, row) {
					var nodes = menuTree.treegrid('getChildren', row.id);
					if (nodes[0] == null && nodes.length <= 0) {
						var node = menuTree.treegrid("find", row.menuParentId);
						menuTree.treegrid("uncheck", node);
						nodes = menuTree.treegrid('getChildren', row.menuParentId);
						for (var i = 0; i < nodes.length; i++) {
							var a = $(".chkFunc[menuId=" + nodes[i].id + "]");
							a.each(function() {
								$(this).prop("checked", false);
							});
						}
					} else {
						var node = menuTree.treegrid("find", row.id);
						menuTree.treegrid("uncheck", node);
						nodes = menuTree.treegrid('getChildren', row.id);
						for (var i = 0; i < nodes.length; i++) {
							var a = $(".chkFunc[menuId=" + nodes[i].id + "]");
							a.each(function() {
								$(this).prop("checked", false);
							});
						}
					}
				}
			} ],
			onDblClickRow : function(row) {
				var nodes = menuTree.treegrid('getChildren', row.id);
				if (nodes[0] != null && nodes.length >= 0) {
					return false;
				}
				var node = menuTree.treegrid("find", row.id);
				menuTree.treegrid("check", node);
				var a = $(".chkFunc[menuId=" + row.id + "]");
				a.each(function() {
					$(this).prop("checked", true);
				});
			}
		});
		$("#btn-delete").click(function() {
			multiDeleteDataGrid($("#grid"), "${ctx}/basic/role/multiDelete");
		});
		$("#excelExport").click(function() {
			var url = "${ctx}/basic/role/excelExport?" + $.param($("#grid").datagrid('options').queryParams);
			if ($("#grid").datagrid("options").filterRules) {
				url += "&filterRules=" + JSON.stringify($("#grid").datagrid("options").filterRules);
			}
			window.parent.location.href = url;
		});
	});

	function fun_role_add() {
		$("#dlg").dialog("open").dialog("setTitle", "新增角色");
		$("#fm").form("clear");
	}

	function fun_role_edit() {
		var row = $("#grid").datagrid("getSelected");
		if (row == null) {
			showAlert("您未选择任何记录!");
		} else {
			$("#dlg").dialog("open").dialog("setTitle", "编辑角色--[" + row.roleName + "]");
			$("#fm").form("load", row);
		}
	}

	function fun_role_save() {
		$("#fm").form("submit", {
			url : "${ctx}/basic/role/update",
			success : function(data) {
				showInfo("保存成功!");
				$("#dlg").dialog("close");
				$("#grid").datagrid("load");
			}
		});
	}

	//获取该角色下的菜单权限
	function refreshMenuTree() {
		if (!selectedRole) {
			showAlert("请先选择角色");
			return false;
		}
		$.get("${ctx}/basic/role/getRoleMenus?roleId=" + selectedRole.id, function(result) {
			if (result.success && result.obj) {
				menuTree.treegrid("clearChecked");
				for (var i = 0; i < result.obj.length; i++) {
					var node = menuTree.treegrid("find", result.obj[i]);
					if (node) {
						action = "fz";
						menuTree.treegrid("check", node);
					}
				}
				action = "xz";
			} else {
				showAlert(result.msg);
			}
		}, 'json');
	}

	function refreshRoleFunctions() {
		$.get("${ctx}/basic/role/getRoleFunctions?roleId=" + selectedRole.id, function(result) {
			if (result.success && result.obj) {
				$(".chkFunc").removeAttr("checked");
				for (var i = 0; i < result.obj.length; i++) {
					var functionId = result.obj[i];
					$("#" + functionId)[0].checked = true;//使用改方法解决兼容性问题
				}
			} else {
				showAlert(result.msg);
			}
		}, 'json');
	}

	//配置该角色下的菜单权限
	function addRoleRights() {
		//获取当前树形菜单选中的项目
		var nodes = menuTree.treegrid("getChecked");
		if (!selectedRole) {
			showAlert("请先选择角色");
			return false;
		}
		//获取所有已分配菜单
		var menuIds = "";
		var functionIds = "";
		for (var i = 0; i < nodes.length; i++) {
			if (nodes[i].id) {//如果为子节点
				menuIds += (nodes[i].id + ",");
				//获取所有已分配功能,放在循环内确保勾选了菜单的部分才被获取
				$(".chkFunc[menuId=" + nodes[i].id + "]:checked").each(function() {
					functionIds += $(this).attr("id") + ",";
				});
			}
		}
		$.post("${ctx}/basic/role/addRoleRights", {
			roleId : selectedRole.id,
			menuIds : menuIds,
			functionIds : functionIds
		}, function(result) {
			showMsg(result.msg);
			if (result.success) {
			}
		}, 'json');
	}

	//功能配置formatter
	function fmt_functions(val, row) {
		if (val && val.length > 0) {
			var r = "";
			for (var i = 0; i < val.length; i++) {
				r += '<input type="checkbox" class="chkFunc" menuId="'+row.id+'" functionNo="'+val[i].functionNo+'" id="'+val[i].id+'"/><span>'
						+ val[i].functionName + '</span>';
			}
			return r;
		}
	}

	function fmt_check(obj, functionNo) {
		var $this = $(obj);
		if ($this.is(":checked")) {
			var $list = $("#cc").layout("panel", "east").find("div.datagrid-body input[functionNo=" + functionNo + "]");
			$list.each(function() {
				if (menuTree.treegrid('isChecked', $(this).attr("menuId"))) {
					$(this).prop("checked", true);
				}
			});
		} else {
			var $list = $("#cc").layout("panel", "east").find("div.datagrid-body input[functionNo=" + functionNo + "]").prop("checked",
					false);
		}
	}
</script>
</head>
<body>
	<div data-options="region:'center'" data-options="fit:true" style="padding: 1px;">
		<div id="cc" class="easyui-layout" data-options="fit:true" style="width: 680px; height: 440px;">
			<div data-options="region:'center'" style="padding: 1px; witdh: 400px">
				<table id="grid">
				</table>
				<div id="tt" class="row">
				<div class="col-md-12">
					<shiro:hasPermission name="role:update">
					<button id="btn-add" type="button" class="btn btn-primary" onclick="fun_role_add()">
					<span class="glyphicon glyphicon-plus"></span> 新增角色
				</button>
				<button id="btn-edit" type="button" class="btn btn-primary" onclick="fun_role_edit()">
					<span class="glyphicon glyphicon-pencil"></span> 修改
				</button>
					</shiro:hasPermission>
					<shiro:hasPermission name="role:delete">
					<button id="btn-delete" type="button" class="btn btn-danger">
					<span class="glyphicon glyphicon-minus"></span> 删除选中
				</button>
					</shiro:hasPermission>
					<shiro:hasPermission name="role:export">
						<button id="excelExport" type="button" class="btn btn-primary">
					<span class="glyphicon glyphicon-save"></span> Excel导出
				</button>
					</shiro:hasPermission>
					</div>
					<div>
				</div>
				</div>
				<shiro:hasPermission name="role:update">
					<div id="dlg" class="easyui-dialog" style="width: 345px; height: 240px; padding: 10px 20px"
						data-options="resizable:true,modal:true, buttons:'#dlg-btn',closed:true">
						<form id="fm" method="post">
							<input id="id" type="hidden" name="id" />

							<table id="tbl">
								<tr>
									<td><label>角色编号:</label></td>
									<td><input name="roleNo" class="easyui-validatebox" data-options="required:true" /></td>
								</tr>
								<tr>
									<td><label>角色名称:</label></td>
									<td><input name="roleName" class="easyui-validatebox" data-options="required:true" /></td>
								</tr>
							</table>
						</form>
						<div id="dlg-btn">
						<button id="add" type="button" class="btn btn-primary" onclick="fun_role_save();">
							<span class="glyphicon glyphicon-ok"></span> 保存
						</button>
						<button id="edit" type="button" class="btn btn-primary" onclick="$('#dlg').dialog('close');">
							<span class="glyphicon glyphicon-remove"></span> 取消
						</button>
			</div>
					</div>
				</shiro:hasPermission>
			</div>
			<div data-options="region:'east',split: true, collapsible:true" style="padding: 1px; witdh: 500px">
				<table id="menuTree">
					<thead>
						<tr>
							<th field="id" hidden="true"></th>
							<th field="menuParentId" hidden="true"></th>
							<th field="rootId" hidden="true"></th>
							<th field="ck" checkbox="true"></th>
							<th field="menuName" width="250">菜单名称</th>
							<th field="functionForJson" formatter="fmt_functions">功能配置</th>
						</tr>
					</thead>
				</table>
				<div id="menuTool">
					<shiro:hasPermission name="role:update">
					<button id="distribution" type="button" class="btn btn-primary" onclick="addRoleRights();">
					<span class="glyphicon glyphicon-plus"></span> 分配
				</button>
					</shiro:hasPermission>
					<c:forEach items="${normalFunctions}" var="nf">
						<input type="checkbox" onclick="fmt_check(this,'${nf.codeName}');">
					    ${nf.codeValue }
					</c:forEach>
				</div>
			</div>
		</div>
	</div>
</body>
</html>
